<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import { onLoad } from '@dcloudio/uni-app'
import { getBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { useXtxGuess } from '@/composables'
// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getBanner = async () => {
  const res = await getBannerAPI(1)
  bannerList.value = res.result
}

// 获取分类数据
const categoryList = ref<CategoryItem[]>([])
const getCategory = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHot = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

// 猜你喜欢
const { guess, onScrollToLower } = useXtxGuess()

onLoad(() => {
  getBanner()
  getCategory()
  getHot()
})

// 返回顶部功能
const scrollTop = ref(0)
const showBackTop = ref(false) // 控制图片显示
// 滚动监听大于500显示回到顶部按钮
const handleScroll = (e: { detail: { scrollTop: number } }) => {
  showBackTop.value = e.detail.scrollTop > 500
}
const scrollToTop = () => {
  scrollTop.value += 1
  setTimeout(() => {
    scrollTop.value = 0
  }, 50)
}
const isTriggered = ref(false)
// 下拉刷新重新获取数据
const onRefresherrefresh = async () => {
  guess.value?.resetGuess()
  isTriggered.value = true
  await Promise.all([getBanner(), getCategory(), getHot(), guess.value?.getGuess()])
  isTriggered.value = false
}
</script>

<template>
  <CustomNavbar />
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    :scroll-top="scrollTop"
    :scroll-with-animation="true"
    @scrolltolower="onScrollToLower"
    @scroll="handleScroll"
    class="scroll-view"
    scroll-y
  >
    <!-- 通告栏 -->
    <uni-notice-bar
      show-icon
      scrollable
      color="#00bf9c"
      background-color="#e0f2f1"
      text="严选全网品质好物，一键下单即享专属折扣！告别海淘比价，把时间留给更重要的人！"
    />
    <XtxSwiper :list="bannerList" />
    <CategoryPanel :list="categoryList" />
    <HotPanel :list="hotList" />
    <XtxGuess ref="guess" />
  </scroll-view>
  <!-- 回到顶部按钮 -->
  <image
    v-show="showBackTop"
    @tap="scrollToTop"
    src="/static/images/back-to-top.png"
    class="back-to-top"
  />
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;

  .scroll-view {
    flex: 1;
  }

  .back-to-top {
    position: fixed;
    bottom: 100rpx;
    right: 40rpx;
    width: 100rpx;
    height: 100rpx;
    z-index: 999;
    animation: fadeInUp 0.5s forwards;
  }
  @keyframes fadeInUp {
    from {
      transform: translateY(30rpx);
    }
    to {
      transform: translateY(0);
    }
  }
}
</style>
